package com.sinping.qh.service.admin.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.domain.common.UploadImageBase64Bean;
import com.sinping.qh.domain.lab.LabInspectItemRelationDomain;
import com.sinping.qh.domain.lab.LabInspectItemTreeDomain;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.records.*;
import com.sinping.qh.dto.admin.record.*;
import com.sinping.qh.dto.admin.word.ApiCheckRecordCreateWord;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.query.base.QueryParams;
import com.sinping.qh.query.records.AlreadyAuditRecordByAdminQuery;
import com.sinping.qh.query.records.CheckRecordByAdminQuery;
import com.sinping.qh.query.records.HiddenDangerRecordQuery;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.common.UploadImageRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemRelationRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemTreeRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.records.CheckPlanRepository;
import com.sinping.qh.repository.mongo.records.CheckRecordsRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.HighLightRepository;
import com.sinping.qh.repository.mongo.records.impl.RectifyReviewRepositoryImpl;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.ICheckRecordsService;
import com.sinping.qh.service.admin.lab.impl.LabInspectItemServiceTreeImpl;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.time.DateFormatUtil;
import com.sinping.qh.utils.word.Base64Util;
import com.sinping.qh.utils.word.DocumentHandler;
import com.sinping.qh.utils.worddocx.WordTools;
import org.apache.commons.lang3.StringUtils;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;

/**
 * 检查记录实现类
 *
 * @author Tiansx
 * @create 2018-06-02 13:54
 **/
@Service
public class CheckRecordsServiceImpl implements ICheckRecordsService {
    @Autowired
    private HighLightRepository highLightRepository;
    @Autowired
    private HiddenDangerRecordRepository hiddenDangerRecordRepository;
    @Autowired
    private UploadImageRepository uploadImageRepository;
    @Autowired
    private CheckRecordsRepository checkRecordsRepository;
    @Autowired
    private MongoManager mongoManager;
    @Autowired
    private UnitRepository unitRepository;
    @Qualifier("sessionServiceRedisImpl")
    @Autowired
    private ISessionService iSessionService;
    @Autowired
    LabInspectItemServiceTreeImpl iLabInspectItemService;
    @Autowired
    LabInspectItemTreeRepository labInspectItemTreeRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private LaboratoryRepository laboratoryRepository;
    @Autowired
    private CheckPlanRepository checkPlanRepository;
    @Autowired
    private IAddorEditUserServiceImpl iAddorEditUserServiceImpl;

    @Autowired
    private LabInspectItemRelationRepository labInspectItemRelationRepository;

    @Value(value = "${qh.upload.filePath}")
    private String filePath;

    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;


    @Autowired
    private RectifyReviewRepositoryImpl rectifyReviewRepositoryImpl;

    @Override
    public ResDto userSubmitRecordsAudit(HttpServletRequest httpRequest, ApiCheckRecordDto apiCheckRecordDto) {

        if (apiCheckRecordDto.getCheckRecordIdList() == null) {
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        if (apiCheckRecordDto.getCheckRecordIdList().isEmpty()) {
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        /**
         * 0-未检查；1-检查中；2-待审核；3-已审核
         */
        //单个提交校验
        if (apiCheckRecordDto.getCheckRecordIdList().size() == 1) {
            CheckRecord one = checkRecordsRepository.findOne(apiCheckRecordDto.getCheckRecordIdList().get(0));
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不存在，请刷新界面后重新提交");
            }
            if (!(CommonDbConst.CHECKRECORD_STATUS_CHECKING.equals(one.getCheckStatus()) || CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(one.getCheckStatus()))) {
                return new ResDto(Const.SERVER_ERROR, "检查记录状态已更改，请刷新界面");
            }
            UnitDomain unit = unitRepository.findOne(one.getCheckUnitId());
            if (unit == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录中的院系不存在");
            }

        }
        //批量提交校验
        if (apiCheckRecordDto.getCheckRecordIdList().size() >= 2) {
            for (String id : apiCheckRecordDto.getCheckRecordIdList()) {
                CheckRecord one = checkRecordsRepository.findOne(id);
                if (one == null) {
                    return new ResDto(Const.SERVER_ERROR, "检查记录不存在，请刷新界面后重新提交");
                }
                if (CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(one.getCheckStatus())) {
                    return new ResDto(Const.SERVER_ERROR, "未检查的记录，请单独提交审核");
                }
                if (!CommonDbConst.CHECKRECORD_STATUS_CHECKING.equals(one.getCheckStatus())) {
                    return new ResDto(Const.SERVER_ERROR, "检查记录状态已更改，请刷新界面");
                }
                UnitDomain unit = unitRepository.findOne(one.getCheckUnitId());
                if (unit == null) {
                    return new ResDto(Const.SERVER_ERROR, "检查记录中的院系不存在");
                }

            }
        }


        try {
            for (String id : apiCheckRecordDto.getCheckRecordIdList()) {
                CheckRecord one = checkRecordsRepository.findOne(id);
                if (one == null) {
                    //记录不存在
                    continue;
                }
                //未检查记录提交审核保存检查人
                if (CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(one.getCheckStatus())) {
                    CheckPlan checkPlan = checkPlanRepository.findOne(one.getCheckPlanId());
                    if (checkPlan != null) {
                        one.setCheckUser(checkPlan.getCheckUser());
                        one.setUnionUnitUser(checkPlan.getUnionUnitUser());
                        one.setCheckDate(new Date());
                    }

                }

                UnitDomain unit = unitRepository.findOne(one.getCheckUnitId());
                //判断院系是否自动审核 0：否 1：是
                if (CommonDbConst.IS_AUTOMATIC_YES.equals(unit.getIsAutomatic())) {
                    one.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT);
                } else {
                    one.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT);
                }


                one.setUpdateUserId(userSessionDTO.getId());
                one.setGmtModified(new Date());
                checkRecordsRepository.save(one);


                //更改隐患记录中，检查记录状态
                List<HiddendangerRecord> hiddendangerRecordList = hiddenDangerRecordRepository.findAllByCheckId(one.getId());
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecordList) {
                    if (CommonDbConst.IS_AUTOMATIC_YES.equals(unit.getIsAutomatic())) {
                        hiddendangerRecord.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT);
                    } else {
                        hiddendangerRecord.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT);
                    }
                    hiddenDangerRecordRepository.save(hiddendangerRecord);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "提交过程中出错");

        }

        return new ResDto(Const.SUCCESS, "提交成功");
    }

    @Override
    public ResDto deleteHightLight(String id) {
        /**
         * 0-未检查；1-检查中；2-待审核；3-已审核
         */

        try {
            HighLightRecord one = highLightRepository.findOne(id);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "亮点记录不存在，请刷新界面");

            }
            CheckRecord checkRecord = checkRecordsRepository.findOne(one.getCheckId());
            if (checkRecord == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不存在");
            }
            if (CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT.equals(checkRecord.getCheckStatus())
                    || CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(checkRecord.getCheckStatus())) {
                return new ResDto(Const.SERVER_ERROR, "检查记录状态不允许执行删除亮点操作");
            }

            List<UploadImage> allImagesByRoleIdlist = uploadImageRepository.findAllByRoleId(id);
            if (!allImagesByRoleIdlist.isEmpty()) {
                for (UploadImage image : allImagesByRoleIdlist) {
                    String roleId = image.getRoleId();
                    uploadImageRepository.deleteAllByRoleId(roleId);
                }

            }

            highLightRepository.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "删除过程中出错");
        }


        return new ResDto(Const.SUCCESS, "删除亮点记录成功");
    }

    @Override
    public ResDto updateHightLight(HttpServletRequest httpRequest, HighLightRecordDto highLightRecordDto) {

        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }

        if (StringUtils.isNotBlank(highLightRecordDto.getId())) {
            HighLightRecord one = highLightRepository.findOne(highLightRecordDto.getId());
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "亮点记录不存在，请刷新界面");

            }
            CheckRecord checkRecord = checkRecordsRepository.findOne(one.getCheckId());
            if (CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT.equals(checkRecord.getCheckStatus())
                    || CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(checkRecord.getCheckStatus())) {
                return new ResDto(Const.SERVER_ERROR, "检查记录状态不允许执行修改亮点操作");
            }

            one.setUpdateUserId(userSessionDTO.getId());
            one.setDesc(highLightRecordDto.getDesc());
            one.setGmtModified(new Date());
            highLightRepository.save(one);
        }


        return new ResDto(Const.SUCCESS, "修改成功");
    }

    @Override
    public ResDto deleteHiddenDanger(String id) {
        /**
         * 0-未检查；1-检查中；2-待审核；3-已审核
         */
        HiddendangerRecord one = hiddenDangerRecordRepository.findOne(id);
        if (one == null) {
            return new ResDto(Const.SERVER_ERROR, "隐患记录不存在，请刷新界面");

        }
        CheckRecord checkRecord = checkRecordsRepository.findOne(one.getCheckId());
        if (CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT.equals(checkRecord.getCheckStatus())
                || CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(checkRecord.getCheckStatus())) {
            return new ResDto(Const.SERVER_ERROR, "检查记录状态不允许执行删除隐患记录操作");
        }
        List<UploadImage> allImagesByRoleIdlist = uploadImageRepository.findAllByRoleId(id);
        if (!allImagesByRoleIdlist.isEmpty()) {
            for (UploadImage image : allImagesByRoleIdlist) {
                String roleId = image.getRoleId();
                uploadImageRepository.deleteAllByRoleId(roleId);
            }

        }

        try {
            hiddenDangerRecordRepository.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "删除过程中出错");
        }


        return new ResDto(Const.SUCCESS, "删除隐患记录成功");
    }

    @Override
    public ResDto updateHiddenDanger(HttpServletRequest httpRequest, HiddenDangerInspectItemDto hiddendangerRecordDto) {
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        /**
         * 检查项类型  0：院系级缺陷 1：实验室缺陷 2: 危险源隐患
         */
        /**
         * 检查记录状态：0-未检查；1-检查中；2-待审核；3-已审核
         */

        HiddendangerRecord hiddendangerRecord = hiddenDangerRecordRepository.findOne(hiddendangerRecordDto.getId());
        if (hiddendangerRecord == null) {
            return new ResDto(Const.SERVER_ERROR, "隐患记录不存在，请刷新界面");
        }
        CheckRecord record = checkRecordsRepository.findOne(hiddendangerRecord.getCheckId());
        if (record == null) {
            return new ResDto(Const.SERVER_ERROR, "检查记录不存在，请刷新界面");
        }
        if (CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT.equals(record.getCheckStatus())
                || CommonDbConst.CHECKRECORD_STATUS_UNCHECK.equals(record.getCheckStatus())) {
            return new ResDto(Const.SERVER_ERROR, "记录状态已变更，请刷新界面");
        }
        if (!StringUtils.isEmpty(hiddendangerRecordDto.getCheckItemId())) {
            LabInspectItemTreeDomain labInspectItemTreeDomain = labInspectItemTreeRepository.findOne(hiddendangerRecordDto.getCheckItemId());
            if (labInspectItemTreeDomain == null) {
                return new ResDto(Const.SERVER_ERROR, "检查项不存在");
            }
            if ("1".equals(labInspectItemTreeDomain.getItemLevel())) {
                hiddendangerRecord.setCheckItemOne(labInspectItemTreeDomain.getItemName());
                hiddendangerRecord.setCheckItemOneId(labInspectItemTreeDomain.getId());
            }
            if ("2".equals(labInspectItemTreeDomain.getItemLevel())) {
                hiddendangerRecord.setCheckItemTwo(labInspectItemTreeDomain.getItemName());
                hiddendangerRecord.setCheckItemTwoId(labInspectItemTreeDomain.getId());
                if (!StringUtils.isEmpty(labInspectItemTreeDomain.getItemParentId())) {
                    LabInspectItemTreeDomain oneLevel = labInspectItemTreeRepository.findOne(labInspectItemTreeDomain.getItemParentId());
                    if (oneLevel != null) {
                        hiddendangerRecord.setCheckItemOne(oneLevel.getItemName());
                        hiddendangerRecord.setCheckItemOneId(oneLevel.getId());
                    }

                }


            }
            if ("3".equals(labInspectItemTreeDomain.getItemLevel())) {
                hiddendangerRecord.setCheckItemThree(labInspectItemTreeDomain.getItemName());
                hiddendangerRecord.setCheckItemThreeId(labInspectItemTreeDomain.getId());
                if (!StringUtils.isEmpty(labInspectItemTreeDomain.getItemParentId())) {
                    LabInspectItemTreeDomain twoLevel = labInspectItemTreeRepository.findOne(labInspectItemTreeDomain.getItemParentId());
                    hiddendangerRecord.setCheckItemTwo(twoLevel.getItemName());
                    hiddendangerRecord.setCheckItemTwoId(twoLevel.getId());

                    if (!StringUtils.isEmpty(twoLevel.getItemParentId())) {
                        LabInspectItemTreeDomain oneLevel = labInspectItemTreeRepository.findOne(twoLevel.getItemParentId());
                        if (oneLevel != null) {
                            hiddendangerRecord.setCheckItemOne(oneLevel.getItemName());
                            hiddendangerRecord.setCheckItemOneId(oneLevel.getId());
                        }

                    }


                }
            }

        }

        hiddendangerRecord.setDesc(hiddendangerRecordDto.getDesc());
        hiddendangerRecord.setGmtModified(new Date());
        hiddendangerRecord.setUpdateUserId(userSessionDTO.getId());

        try {
            hiddenDangerRecordRepository.save(hiddendangerRecord);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "修改过程中出错");
        }
        return new ResDto(Const.SUCCESS, "修改成功");
    }

    @Override
    public ResDto getCheckInspectItemList(HttpServletRequest request, ApiInspectItemTreeDto apiInspectItemTreeDto) {

        if (CommonDbConst.CHECKRECORD_TYPE_ALL.equals(apiInspectItemTreeDto.getCheckRecordType())) {
            /**
             * 0:院系级缺陷 1：实验室缺陷 2：危险源隐患
             */
            return iLabInspectItemService.getLabInspectItemDescRelation(request, "0", "");

        }
        if (CommonDbConst.CHECKRECORD_TYPE_LAB.equals(apiInspectItemTreeDto.getCheckRecordType())) {

            return iLabInspectItemService.getLabInspectItemDescRelation(request, "1", apiInspectItemTreeDto.getLabId());
        }

        return new ResDto(Const.SERVER_ERROR, "获取失败");
    }

    @Override
    public ResDto getWaitedAuditRecordList(HttpServletRequest httpRequest, FrontPage page) {
        Integer pageSize = page.getSize();
        Integer pageNum = page.getPage();

        //2.Map conditionMap
        Map<String, Object> conditionMap = page.getCondition();

        CheckRecordByAdminQuery checkRecoredsQuery = new CheckRecordByAdminQuery();
        checkRecoredsQuery.setCheckUnitId((String) conditionMap.get("check_unit_id"));
        checkRecoredsQuery.setCheckBuildingId((String) conditionMap.get("check_building_id"));
        checkRecoredsQuery.setCheckStatus((String) conditionMap.get("check_status"));
        try {
            String startDate = (String) conditionMap.get("start_date");
            String endDate = (String) conditionMap.get("end_date");
            if (!StringUtils.isEmpty(startDate)) {
                checkRecoredsQuery.setStartDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, startDate));
            } else {
                checkRecoredsQuery.setStartDate(null);

            }
            if (!StringUtils.isEmpty(endDate)) {
                checkRecoredsQuery.setEndDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, endDate));
            } else {
                checkRecoredsQuery.setEndDate(null);

            }
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResDto(Const.PARAM_ERROR, "时间格式不正确");

        }
        String order = "DESC";
        if (!StringUtils.isEmpty(page.getOrder())) {
            if ("ASC".equals(page.getOrder().toUpperCase())) {
                order = "ASC";
            }
        }
        String prop = "gmt_created";
        if (!StringUtils.isEmpty(page.getProp())) {
            prop = page.getProp();
        }
        //设置查询条件
        Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.fromString(order), prop));
        //6.用MongoManager去查询的数据
        Page<CheckRecord> pageResult = mongoManager.findPage(checkRecoredsQuery, pageRequest, CheckRecord.class);

        //7.把查询结果放到FrontPage中返回到接口
        ResDto resDto = new ResDto(ConstEum.SUCCESS);


        List<ApiCheckRecordDto> apiCheckRecordDtoList = BeanMapper.mapList(pageResult, ApiCheckRecordDto.class);

        for (ApiCheckRecordDto apiCheckRecordDto : apiCheckRecordDtoList) {
            //查找隐患数
            HiddenDangerRecordQuery hiddenDangerRecordQuery = new HiddenDangerRecordQuery();
            hiddenDangerRecordQuery.setCheckId(apiCheckRecordDto.getId());
            long hiddenDangerCount = mongoManager.count(hiddenDangerRecordQuery, HiddendangerRecord.class);
            apiCheckRecordDto.setHiddenDangerCount(hiddenDangerCount + "");

        }

        long totalPages = pageResult.getTotalPages();
        int currentPage = page.getPage();
        page = new FrontPage();
        page.setPage(currentPage);
        page.setTotal((int) pageResult.getTotalElements());
        page.setPages((int) totalPages);
        page.setRecords(apiCheckRecordDtoList);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(page));


        return resDto;
    }

    @Override
    public ResDto getWaitedAuditRecordDetail(String id) {

        try {
            CheckRecord one = checkRecordsRepository.findOne(id);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不存在");
            }
            ApiCheckRecordDto apiCheckRecordDto = BeanMapper.map(one, ApiCheckRecordDto.class);
            List<HighLightRecord> highLightRecordList = highLightRepository.findAllByCheckId(id);
            List<HiddendangerRecord> hiddendangerRecordsList = hiddenDangerRecordRepository.findAllByCheckId(id);
            apiCheckRecordDto.setHighLightRecordList(highLightRecordList);
            apiCheckRecordDto.setHiddendangerRecordList(hiddendangerRecordsList);
            String data = JsonMapper.defaultMapper().toJson(apiCheckRecordDto);
            return new ResDto(ConstEum.SUCCESS, data);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "获取检查记录异常");
        }


    }

    @Override
    public ResDto auditPass(HttpServletRequest httpRequest, ApiCheckRecordDto apiCheckRecordDto) {

        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        if (apiCheckRecordDto.getCheckRecordIdList() == null) {
            return new ResDto(Const.SERVER_ERROR, "参数id不能为空");
        }
        if (apiCheckRecordDto.getCheckRecordIdList().isEmpty()) {
            return new ResDto(Const.SERVER_ERROR, "参数id不能为空");
        }

        for (String id : apiCheckRecordDto.getCheckRecordIdList()) {
            CheckRecord one = checkRecordsRepository.findOne(id);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不存在，请刷新界面后重新提交");
            }
            if (!CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT.equals(one.getCheckStatus())) {
                return new ResDto(Const.SERVER_ERROR, "存在非待审核状态的记录，请刷新记录列表后重试");
            }

        }
        //TODO 批量处理，出现异常情况数据还原
        for (String id : apiCheckRecordDto.getCheckRecordIdList()) {

            CheckRecord one = checkRecordsRepository.findOne(id);
            if (one == null) {
                //记录不存在
                continue;
            }
            if (!CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT.equals(one.getCheckStatus())) {
                //记录状态不是待审核
                continue;
            }
            one.setExamineAdvice(apiCheckRecordDto.getExamineAdvice());
            one.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT);
            try {
                checkRecordsRepository.save(one);
                //更改隐患记录中，检查记录状态
                List<HiddendangerRecord> hiddendangerRecordList = hiddenDangerRecordRepository.findAllByCheckId(one.getId());
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecordList) {
                    hiddendangerRecord.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT);
                    hiddenDangerRecordRepository.save(hiddendangerRecord);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new ResDto(Const.SERVER_ERROR, "更改记录状态时出错");
            }

        }


        return new ResDto(Const.SUCCESS, "操作成功");
    }

    @Override
    public ResDto getAlreadyAuditRecordList(HttpServletRequest request, FrontPage frontPage) {
        /**
         * 获取当前用户id
         */
        String token = request.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        Integer pageSize = frontPage.getSize();
        Integer pageNum = frontPage.getPage();

        //2.Map conditionMap
        Map<String, Object> conditionMap = frontPage.getCondition();
        AlreadyAuditRecordByAdminQuery checkRecoredsQuery = new AlreadyAuditRecordByAdminQuery();
        checkRecoredsQuery.setCheckUnitId((String) conditionMap.get("check_unit_id"));
        checkRecoredsQuery.setCheckBuildingId((String) conditionMap.get("check_building_id"));
        checkRecoredsQuery.setCheckStatus((String) conditionMap.get("check_status"));
        checkRecoredsQuery.setCheck_lab((String) conditionMap.get("check_lab"));
        checkRecoredsQuery.setOffices((String) conditionMap.get("offices"));
        try {
            String startDate = (String) conditionMap.get("start_date");
            String endDate = (String) conditionMap.get("end_date");

            if (!StringUtils.isEmpty(startDate)) {
                checkRecoredsQuery.setStartDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, startDate));
            } else {
                checkRecoredsQuery.setStartDate(null);
            }
            if (!StringUtils.isEmpty(endDate)) {
                checkRecoredsQuery.setEndDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, endDate));
            } else {
                checkRecoredsQuery.setEndDate(null);

            }
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResDto(Const.PARAM_ERROR, "时间格式不正确");

        }
        String order = "DESC";
        if (!StringUtils.isEmpty(frontPage.getOrder())) {
            if ("ASC".equals(frontPage.getOrder().toUpperCase())) {
                order = "ASC";
            }
        }
        String prop = "check_date";
        if (!StringUtils.isEmpty(frontPage.getProp())) {
            prop = frontPage.getProp();
        }
        //设置查询条件
        Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.fromString(order), prop));

        //7.把查询结果放到FrontPage中返回到接口
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        //查询符合条件的检查记录
        List<CheckRecord> apiCheckRecordUserManagerListPage =
                findUserMangerUnitOrLibCheckRecord(checkRecoredsQuery, pageRequest, userSessionDTO, CheckRecord.class, CheckRecord.class);
        List<CheckRecord> apiCheckRecordDtoUserManagerList =
                findUserMangerUnitOrLibCheckRecord(checkRecoredsQuery, null, userSessionDTO, CheckRecord.class, CheckRecord.class);

        List<ApiCheckRecordDto> apiCheckRecordDtoUserManagerListPage = BeanMapper.mapList(apiCheckRecordUserManagerListPage, ApiCheckRecordDto.class);

        for (ApiCheckRecordDto apiCheckRecordDto : apiCheckRecordDtoUserManagerListPage) {
            //查找隐患数
            HiddenDangerRecordQuery hiddenDangerRecordQuery = new HiddenDangerRecordQuery();
            hiddenDangerRecordQuery.setCheckId(apiCheckRecordDto.getId());
            long hiddenDangerCount = mongoManager.count(hiddenDangerRecordQuery, HiddendangerRecord.class);
            apiCheckRecordDto.setHiddenDangerCount(hiddenDangerCount + "");

            //整改隐患数
            HiddenDangerRecordQuery rectifyQuery = new HiddenDangerRecordQuery();
            rectifyQuery.setCheckId(apiCheckRecordDto.getId());
            rectifyQuery.setHiddenDangerStatus(CommonDbConst.HIDDENDANGER_STATUS_CLOSE);
            long rectifyCount = mongoManager.count(rectifyQuery, HiddendangerRecord.class);
            apiCheckRecordDto.setRectifyCount(rectifyCount + "");
        }

        Page<ApiCheckRecordDto> pagesResult = new PageImpl<>(apiCheckRecordDtoUserManagerListPage, pageRequest, apiCheckRecordDtoUserManagerList.size());
        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto, pagesResult, ApiCheckRecordDto.class, frontPage);
        return resDto;
    }

    @Override
    public ResDto deleteRecordImage(ApiRecordImageDto apiRecordImageDto) {
        UploadImage image = uploadImageRepository.findOne(apiRecordImageDto.getImageId());
        if (image == null) {
            return new ResDto(Const.SERVER_ERROR, "图片已被删除");
        }
        //亮点
        if ("1".equals(apiRecordImageDto.getType())) {
            HighLightRecord highLightRecord = highLightRepository.findOne(apiRecordImageDto.getId());
            if (highLightRecord == null) {
                return new ResDto(Const.SERVER_ERROR, "亮点记录不存在");
            }
            List<UploadImage> uploadImageList = highLightRecord.getUploadImageList();
            List<UploadImage> newUploadImageList = new ArrayList<>();
            if (uploadImageList == null) {
                return new ResDto(Const.SERVER_ERROR, "该记录无图片");
            }
            if (uploadImageList.isEmpty()) {
                return new ResDto(Const.SERVER_ERROR, "该记录无图片");
            }

            for (UploadImage uploadImage : uploadImageList) {
                if (!apiRecordImageDto.getImageId().equals(uploadImage.getId())) {
                    newUploadImageList.add(uploadImage);
                }
            }
            highLightRecord.setUploadImageList(newUploadImageList);
            highLightRepository.save(highLightRecord);
//            uploadImageRepository.delete(apiRecordImageDto.getImageId());
        }
        //隐患
        if ("2".equals(apiRecordImageDto.getType())) {
            HiddendangerRecord hiddendangerRecord = hiddenDangerRecordRepository.findOne(apiRecordImageDto.getId());
            if (hiddendangerRecord == null) {
                return new ResDto(Const.SERVER_ERROR, "隐患记录不存在");
            }

            List<UploadImage> uploadImageList = hiddendangerRecord.getUploadImageList();
            List<UploadImage> newUploadImageList = new ArrayList<>();

            if (uploadImageList == null) {
                return new ResDto(Const.SERVER_ERROR, "该记录无图片");
            }
            if (uploadImageList.isEmpty()) {
                return new ResDto(Const.SERVER_ERROR, "该记录无图片");
            }

            for (UploadImage uploadImage : uploadImageList) {
                if (!apiRecordImageDto.getImageId().equals(uploadImage.getId())) {
                    newUploadImageList.add(uploadImage);
                }
            }
            hiddendangerRecord.setUploadImageList(newUploadImageList);
            hiddenDangerRecordRepository.save(hiddendangerRecord);
//            uploadImageRepository.delete(apiRecordImageDto.getImageId());


        }

        return new ResDto(ConstEum.SUCCESS, "删除成功");
    }

    @Override
    public ResDto generateCheckReport(ApiCheckRecordReportDto apiCheckRecordReportDto) {

        List<String> checkRecordIds = apiCheckRecordReportDto.getCheckRecordIds();
        List<String> hiddenDangerStatusList = apiCheckRecordReportDto.getHiddenDangerStatus();
        List<String> unitIds = new ArrayList<>();
        List<CheckRecord> checkRecordList = new ArrayList<>();
        String unitName = null;
        for (String checkRecordId : checkRecordIds) {
            CheckRecord one = checkRecordsRepository.findOne(checkRecordId);
            if (!unitIds.contains(one.getCheckUnitId())) {
                unitIds.add(one.getCheckUnitId());
            }
            if (unitIds.size() > 1) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不属于同一个院系，请重新选择");
            }
            if (!StringUtils.isNotBlank(unitName)) {
                unitName = one.getCheckUnit();
            }
            checkRecordList.add(one);
        }
        //检查记录
        List<ApiCheckRecordDto> apiCheckRecordDtoList = BeanMapper.mapList(checkRecordList, ApiCheckRecordDto.class);

        //综合检查记录
        List<ApiCheckRecordDto> unitCheckRecordDtos = new ArrayList<ApiCheckRecordDto>();
        //实验室检查记录
        List<ApiCheckRecordDto> labCheckRecordDtos = new ArrayList<ApiCheckRecordDto>();

        //综合隐患记录
        List<HiddendangerRecordDto> unitHiddendangerDtos = new ArrayList<HiddendangerRecordDto>();
        //实验室隐患记录
        List<HiddendangerRecordDto> labHiddendangerDtos = new ArrayList<HiddendangerRecordDto>();
        //循环检查记录
        if (null != apiCheckRecordDtoList && apiCheckRecordDtoList.size() > 0) {
            for (int j = 0; j < apiCheckRecordDtoList.size(); j++) {
                ApiCheckRecordDto checkRecordDto = apiCheckRecordDtoList.get(j);

                /** 区分综合检查记录和实验室检查记录**/
                //综合检查记录
                if (null != checkRecordDto && checkRecordDto.getCheckType().equals("0")) {
                    //1.添加亮点
                    HighLightRecord light = highLightRepository.findHighLightRecordByCheckId(checkRecordDto.getId());
                    if (null != light) {
                        HighLightRecordDto lightDto = BeanMapper.map(light, HighLightRecordDto.class);
                        HighLightRecordDto lightBase64Dto = picPathToBase64(lightDto);
                        checkRecordDto.setUnitHighLightRecord(lightBase64Dto);
                        //2.添加隐患to综合隐患记录中(区分)
                        addHiddenDangerToDto(hiddenDangerStatusList, unitHiddendangerDtos, checkRecordDto);
                        checkRecordDto.setUnitRecords(unitHiddendangerDtos);
                        //放入综合检查记录的集合中
                        unitCheckRecordDtos.add(checkRecordDto);
                    }
                }
                //实验室检查记录
                if (null != checkRecordDto && checkRecordDto.getCheckType().equals("1")) {
                    //添加实验室的负责人和危险源等级
                    String checkLabId = checkRecordDto.getCheckLabId();
                    if (StringUtils.isNotBlank(checkLabId)) {
                        LaboratoryDomain one = laboratoryRepository.findOne(checkLabId);
                        String riskManager = one.getRiskManager();
                        String riskLevel = one.getRiskLevel();

                        //得到一级的检查项名称
                        List<String> labInspectItemNames = new ArrayList<>();
                        //先查关系表
                        List<LabInspectItemRelationDomain> relationDomains = labInspectItemRelationRepository.findByLabId(checkLabId);
                        if (null != relationDomains && relationDomains.size() > 0) {
                            for (int i = 0; i < relationDomains.size(); i++) {
                                String inspectItemId = relationDomains.get(i).getInspectItemId();
                                //再查检查项表
                                LabInspectItemTreeDomain item = labInspectItemTreeRepository.findOne(inspectItemId);
                                if (item.getItemLevel().equals("1")) {
                                    //检查项类型是危险源：item_category为0
                                    if (item.getItemCategory().equals("0")) {
                                        String itemName = item.getItemName();
                                        if (!labInspectItemNames.contains(itemName)) {
                                            labInspectItemNames.add(itemName);
                                        }
                                    }
                                } else {
                                    LabInspectItemTreeDomain item2 = labInspectItemTreeRepository.findOne(item.getItemParentId());
                                    //检查项类型是危险源：item_category为0
                                    if (item2.getItemCategory().equals("0")) {
                                        String itemName2 = item2.getItemName();
                                        if (!labInspectItemNames.contains(itemName2)) {
                                            labInspectItemNames.add(itemName2);
                                        }
                                    }
                                }
                            }
                        }

                        if (labInspectItemNames.size() > 0) {
                            StringBuffer buffer = new StringBuffer();
                            for (String nameStr : labInspectItemNames) {
                                buffer.append(nameStr).append(";");
                            }
                            checkRecordDto.setLabInspectItemNameStrs(buffer.toString());
                        }
                        checkRecordDto.setRiskLevel(riskLevel);
                        checkRecordDto.setRiskManager(riskManager);
                    }

                    //1.添加亮点
                    HighLightRecord light = highLightRepository.findHighLightRecordByCheckId(checkRecordDto.getId());
                    HighLightRecordDto lightDto = new HighLightRecordDto();
                    if (light != null) {
                        lightDto = BeanMapper.map(light, HighLightRecordDto.class);
                    }

                    HighLightRecordDto lightBase64Dto = picPathToBase64(lightDto);
                    checkRecordDto.setLabHighLightRecord(lightBase64Dto);
                    //2.添加隐患to实验室隐患记录中(区分)
                    addHiddenDangerToDto(hiddenDangerStatusList, labHiddendangerDtos, checkRecordDto);
                    checkRecordDto.setLabRecords(labHiddendangerDtos);
                    //放入实验室检查记录的集合中
                    labCheckRecordDtos.add(checkRecordDto);
                }
            }
        }

        ApiCheckRecordCreateWord checkReportWord = new ApiCheckRecordCreateWord();
        checkReportWord.setUnitName(unitName);
        checkReportWord.setUnitCheckRecords(unitCheckRecordDtos);
        checkReportWord.setLabCheckRecords(labCheckRecordDtos);

        //生成word整改报告
        Map<String, Object> datasMap = new HashMap<String, Object>(6);
        datasMap.put("checkReportWord", checkReportWord);


        //生成word文档
        DocumentHandler documentHandler = new DocumentHandler();
        ResDto resDto = new ResDto();
        try {
            /**导出doc2003代码 start**/
            //本地测试代码
            //documentHandler.createDoc("template_checkrecord.ftl", datasMap, "E:/checkRecord" + (new Date().getTime()) + ".doc");
            //documentHandler.createDoc("template_checkrecord.ftl",datasMap,   filePath+"检查表填写界面"+ new Date().getTime()+ ".doc");

//            //服务器代码
//            //拼接服务器上的路径地址
//            String path = "/word/";
//            String roleId = "1";
//            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
//            path += roleId + "/" + date + "/";
//            //保存文件
//            String exprotFilepath = filePath + path;
//            File dir = new File(exprotFilepath);
//            //File dir = new File(path);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            //保存word的地址
//            String fileName = "checkRecord" + new Date().getTime() + ".docx";
//            String saveFileNameAndPath = exprotFilepath + fileName;
//
//            /**导出doc2003代码 start**/
//            documentHandler.createDoc("template_checkrecord.ftl", datasMap, saveFileNameAndPath);
//            /**导出doc2003代码 end**/
//            resDto.setStatus(Const.SUCCESS);
//            resDto.setMsg("成功");
//
//            //下载word的地址
//            String downLoadFileNameAndPath = urlPath + path + fileName;
//            resDto.setDatas(downLoadFileNameAndPath);
            /**导出doc2003代码 end**/

            /**导出docx2013代码 start**/
//            //本地测试代码
//            File resumeFile = WordTools.createDoc("D:\\word\\template_checkrecord_2013.xml", datasMap, "template_checkrecord_2013.ftl");
//            WordprocessingMLPackage wmlPackage = null;
//            try {
//                wmlPackage = (WordprocessingMLPackage) WordprocessingMLPackage.load(new FileInputStream(resumeFile));
//            } catch (Docx4JException e) {
//                e.printStackTrace();
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//            File file = new File("D:\\word\\template_checkrecord_2013.docx");
//            try {
//                wmlPackage.save(file, Docx4J.FLAG_SAVE_ZIP_FILE);
//            } catch (Docx4JException e) {
//                e.printStackTrace();
//            }

            //拼接服务器上的路径地址
            String path = "/word/";
            String roleId = "1";
            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
            path += roleId + "/" + date + "/";
            //保存文件
            String exprotFilepath = filePath + path;
            File dir = new File(exprotFilepath);
            //File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //保存word的地址
            String fileName = "checkRecord" + new Date().getTime() + ".docx";
            String saveFileNameAndPath = exprotFilepath + fileName;
            //生成docx 2013word
            File resumeFile = WordTools.createDoc("template_checkrecord_2013.xml", datasMap, "template_checkrecord_2013.ftl");
            WordprocessingMLPackage wmlPackage = null;
            try {
                wmlPackage = (WordprocessingMLPackage) WordprocessingMLPackage.load(new FileInputStream(resumeFile));
            } catch (Docx4JException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File file = new File(saveFileNameAndPath);
            try {
                wmlPackage.save(file, Docx4J.FLAG_SAVE_ZIP_FILE);
            } catch (Docx4JException e) {
                e.printStackTrace();
            }

            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");

            //下载word的地址
            String downLoadFileNameAndPath = urlPath + path + fileName;
            resDto.setDatas(downLoadFileNameAndPath);
            /**导出docx2013代码 end**/
        } catch (Exception e) {//UnsupportedEncodingException e
            e.printStackTrace();
            resDto.setStatus(Const.DATA_ERROR);
            resDto.setMsg("生成检查报告异常");
        }
        return resDto;
    }

    /**
     * 添加隐患到检查记录中
     *
     * @param hiddenDangerStatusList
     * @param checkRecordDto
     */
    private List<HiddendangerRecordDto> addHiddenDangerToDto(List<String> hiddenDangerStatusList, List<HiddendangerRecordDto> unitOrLabHiddendangerDtos, ApiCheckRecordDto checkRecordDto) {
        List<String> checkIds = new ArrayList<>();
        checkIds.add(checkRecordDto.getId());
        //根据记录id和隐患状态，查出符合条件的隐患记录
        List<HiddendangerRecord> hdRecordDomains = findHiddenRecordInCheck(checkIds, hiddenDangerStatusList, HiddendangerRecord.class, HiddendangerRecord.class);
        List<HiddendangerRecordDto> hdRecordDtos = BeanMapper.mapList(hdRecordDomains, HiddendangerRecordDto.class);

        for (int k = 0; k < hdRecordDtos.size(); k++) {
            HiddendangerRecordDto hiddendangerDto = hdRecordDtos.get(k);

            //添加整改复查信息
            List<RectifyReviewDto> zgList = rectifyReviewRepositoryImpl.findRectifyReview(hiddendangerDto.getId(), "0", RectifyReviewDomain.class, RectifyReviewDto.class);
            //查最新的整改信息
            List<RectifyReviewDto> fcList = rectifyReviewRepositoryImpl.findRectifyReview(hiddendangerDto.getId(), "1", RectifyReviewDomain.class, RectifyReviewDto.class);

            if (null != zgList && zgList.size() > 0) {
                RectifyReviewDto zgDto = zgList.get(0);
                //整改有图片,转成Base64
                RectifyReviewDto zgBase64Dto = zgfcPicPathToBase64(zgDto);
                hiddendangerDto.setZhengGaiInfo(zgBase64Dto);
            }
            if (null != fcList && fcList.size() > 0) {
                RectifyReviewDto fcDto = fcList.get(0);
                //复查有图片,转成Base64
                RectifyReviewDto fcBase64Dto = zgfcPicPathToBase64(fcDto);
                hiddendangerDto.setFuChaInfo(fcBase64Dto);
            }
            //隐患图片
            HiddendangerRecordDto hiddendangerBase64Dto = picPathToBase64(hiddendangerDto);
            unitOrLabHiddendangerDtos.add(hiddendangerBase64Dto);
        }

        return unitOrLabHiddendangerDtos;

    }

    /**
     * 亮点图片转成Base64编码
     *
     * @param highLightRecordDto
     */
    public HighLightRecordDto picPathToBase64(HighLightRecordDto highLightRecordDto) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = highLightRecordDto.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());
                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());

                    base64List.add(base64Bean);
                }
            }
        }
        highLightRecordDto.setUploadImageBase64(base64List);
        return highLightRecordDto;
    }


    /**
     * 隐患图片转成Base64编码
     *
     * @param hiddendangerRecord
     */
    public HiddendangerRecordDto picPathToBase64(HiddendangerRecordDto hiddendangerRecord) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = hiddendangerRecord.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());

                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        hiddendangerRecord.setUploadImageBase64(base64List);
        return hiddendangerRecord;
    }

    /**
     * 整改复查图片转成Base64编码
     *
     * @param rectifyReviewDto
     */
    public RectifyReviewDto zgfcPicPathToBase64(RectifyReviewDto rectifyReviewDto) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = rectifyReviewDto.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());

                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        rectifyReviewDto.setUploadImageBase64(base64List);
        return rectifyReviewDto;
    }


    /**
     * 获取用户负责院系或实验室的检查记录
     *
     * @param userSessionDTO
     * @param clazz
     * @param targetClazz
     * @param <T>
     * @return
     */
    public <T> List<T> findUserMangerUnitOrLibCheckRecord(QueryParams params, Pageable pageRequest, UserSessionDTO userSessionDTO, Class<?> clazz, Class<T> targetClazz) {

        try {
            List<AggregationOperation> operations = Lists.newArrayList();
            Criteria mainCriteria = new Criteria();
            List<String> units = new ArrayList<>();
            List<String> libs = new ArrayList<>();
            List<String> userManagerUnitIdList = iAddorEditUserServiceImpl.getUserManagerUnitIdOrLabIdList(userSessionDTO.getId(), CommonDbConst.USER_MANAGER_UNIT);
            List<String> userManagerLabIdList = iAddorEditUserServiceImpl.getUserManagerUnitIdOrLabIdList(userSessionDTO.getId(), CommonDbConst.USER_MANAGER_LAB);
            if (userManagerUnitIdList != null) {
                units = userManagerUnitIdList;
            }
            if (userManagerLabIdList != null) {
                libs = userManagerLabIdList;
            }
            Criteria one = Criteria.where("check_unit_id").in(units);
            Criteria two = Criteria.where("check_lab_id").in(libs);
            Criteria three = mongoManager.where(params);

            mainCriteria.orOperator(one, two).andOperator(three);
            operations.add(Aggregation.match(mainCriteria));
            if (pageRequest != null) {
                SortOperation sortOperation = new SortOperation(pageRequest.getSort());
                operations.add(sortOperation);
                SkipOperation skipOperation = new SkipOperation(pageRequest.getOffset());
                operations.add(skipOperation);
                LimitOperation limitOperation = new LimitOperation(pageRequest.getPageSize());
                operations.add(limitOperation);

            }
            Aggregation aggregation = Aggregation.newAggregation(operations);
            String table = template.getCollectionName(clazz);
            AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);


            return results.getMappedResults();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();

    }

    /**
     * 查找符合隐患状态的隐患记录
     *
     * @param hiddenDangerStatusList
     * @param clazz
     * @param targetClazz
     * @param <T>
     * @return
     */
    public <T> List<T> findHiddenRecordInCheck(List<String> checkRecordIdList, List<String> hiddenDangerStatusList, Class<?> clazz, Class<T> targetClazz) {

        try {
            List<AggregationOperation> operations = Lists.newArrayList();
            Criteria mainCriteria = new Criteria();

            Criteria one = Criteria.where("hidden_danger_status").in(hiddenDangerStatusList);
            Criteria two = Criteria.where("check_id").in(checkRecordIdList);
            mainCriteria.andOperator(one, two);
            operations.add(Aggregation.match(mainCriteria));

            Aggregation aggregation = Aggregation.newAggregation(operations);
            String table = template.getCollectionName(clazz);
            AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);

            return results.getMappedResults();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();

    }

    @Override
    public ResDto callback(HttpServletRequest request, ApiCheckRecordDto apiCheckRecordDto) {

        /**
         * 获取当前用户id
         */
        String token = request.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);

        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        if (apiCheckRecordDto.getCheckRecordIdList() == null) {
            return new ResDto(Const.SERVER_ERROR, "参数id不能为空");
        }
        if (apiCheckRecordDto.getCheckRecordIdList().isEmpty()) {
            return new ResDto(Const.SERVER_ERROR, "参数id不能为空");
        }

        List<CheckRecord> checkRecordList = new ArrayList<>();
        for (String id : apiCheckRecordDto.getCheckRecordIdList()) {
            CheckRecord one = checkRecordsRepository.findOne(id);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "检查记录不存在，请刷新界面后重新提交");
            }
            if (!CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT.equals(one.getCheckStatus())) {
                return new ResDto(Const.SERVER_ERROR, "存在非待审核状态的记录，请刷新记录列表后重试");
            }
            checkRecordList.add(one);
        }

        for (CheckRecord one : checkRecordList) {
            one.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CHECKING);
            one.setUpdateUserId(userSessionDTO.getId());
            one.setGmtModified(new Date());
            checkRecordsRepository.save(one);
            try {
                //更改隐患记录中，检查记录状态
                List<HiddendangerRecord> hiddendangerRecordList = hiddenDangerRecordRepository.findAllByCheckId(one.getId());
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecordList) {
                    hiddendangerRecord.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CHECKING);
                    hiddenDangerRecordRepository.save(hiddendangerRecord);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new ResDto(Const.SERVER_ERROR, "更改记录状态时出错");
            }
        }
        return new ResDto(Const.SUCCESS, "提交成功");
    }
}
